//
//  OrdineRigheVC.m
//  iTeVe
//
//  Created by Pedro Gonzalez on 03/03/14.
//  Copyright (c) 2014 SISI Software. All rights reserved.
//

#import "OrdineRigheVC.h"
#import "DettaglioCell.h"
#import "RigaDettaglio.h"
#import "RigaDettaglioEditVC.h"

@interface OrdineRigheVC ()


@end




@implementation OrdineRigheVC {
    
}

//@synthesize modelDettaglio, modelRiga;
@synthesize modelRiga, modelTesta;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    self.navigationItem.title = NSLocalizedString(@"TABELLA_ORDINI", @"Tabella ordini...");
//    self.navigationItem.prompt = @"iTeVe";
    [self populateOrdini:@""];
    
    [super setEditing:YES animated:YES]; // per mettere in modo edit -  e far comparire i pulsanti di cancellazione a sinistra. (editingStyleForRowAtIndexPath)
}


-(void) populateOrdini:(NSString *)filtro
{
    
    righeDettaglio = modelTesta.righeDocumento;
//    righeDettaglio = [[NSMutableArray alloc] init];
//    FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
//    righeDettaglio = [db getDettaglio:@""];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [righeDettaglio count]+1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"DettaglioCell";
    DettaglioCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    int count = 0;
    if (indexPath.row != 0){
        count = 1;
    }
    
    if (indexPath.row == ([righeDettaglio count])){
        cell.lblCodice.text = @"Aggiungi";
//        CGRect labelFrame = cell.lblCodice.frame;
        //        cell.lblCodice.frame = labelFrame;
        /*
        labelFrame.size = [cell.lblCodice.text sizeWithFont:cell.lblCodice.font
                                    constrainedToSize:CGSizeMake(cell.lblCodice.frame.size.width, CGFLOAT_MAX)
                                        lineBreakMode:cell.lblCodice.lineBreakMode];
         */
        
        
        cell.lblCodice.frame = [cell.lblCodice.text boundingRectWithSize:CGSizeMake(300.f, CGFLOAT_MAX)
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                                              attributes:@{NSFontAttributeName:cell.lblCodice.font}
                                             context:nil];
        
//        cell.lblCodice.frame = labelFrame;
        


        cell.lblDescrizione.hidden = YES;
        cell.tfQuantita.hidden = YES;
        cell.tfPrezzo.hidden = YES;
        cell.tfUM.hidden = YES;
        cell.tfTotaleRiga.hidden = YES;
        cell.btnModificaRiga.hidden = YES;
        return cell;
    }

    RigaDettaglio *rigaDettaglio = [righeDettaglio objectAtIndex:[indexPath row]];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd/MM/yyyy"];
    cell.lblCodice.text = rigaDettaglio.codart;
    cell.lblDescrizione.text = rigaDettaglio.descrizione;
    
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [numberFormatter setNegativeFormat:@"(0.00)"];
    [numberFormatter setPositiveFormat:@"0.00"];
    
    NSNumberFormatter *numberFormatter3 = [[NSNumberFormatter alloc] init];
    [numberFormatter3 setNumberStyle:NSNumberFormatterDecimalStyle];
    [numberFormatter3 setNegativeFormat:@"(0.000)"];
    [numberFormatter3 setPositiveFormat:@"0.000"];
    
    cell.tfQuantita.text = [numberFormatter3 stringFromNumber:rigaDettaglio.quantita];
    cell.tfPrezzo.text = [numberFormatter stringFromNumber:rigaDettaglio.prezzo];
    cell.tfUM.text = [NSString localizedStringWithFormat:@"%@", rigaDettaglio.unmisura, nil];
    cell.tfTotaleRiga.text = [numberFormatter stringFromNumber:rigaDettaglio.totaleivato];
    
    cell.lblDescrizione.hidden = NO;
    cell.tfQuantita.hidden = NO;
    cell.tfPrezzo.hidden = NO;
    cell.tfUM.hidden = NO;
    cell.tfTotaleRiga.hidden = NO;
    cell.btnModificaRiga.hidden = NO;
    cell.btnModificaRiga.tag=indexPath.row;

    
    cell.accessoryType = UITableViewCellAccessoryDetailButton;
    
    return cell;
}



 // The editing style for a row is the kind of button displayed to the left of the cell when in editing mode.
 - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
 // No editing style if not editing or the index path is nil.
 
 // Determine the editing style based on whether the cell is a placeholder for adding content or already
 // existing content. Existing content can be deleted.
     
 if (indexPath.row == ([righeDettaglio count])) {
     return UITableViewCellEditingStyleInsert;
 } else {
     return UITableViewCellEditingStyleDelete;
 }
     return UITableViewCellEditingStyleNone;
 }




- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // cancello o aggiungo riga
    rigaAttuale = -1;
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [righeDettaglio removeObjectAtIndex:indexPath.row];
        [self.tableView reloadData];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        RigaDettaglio *rigaDettaglio = [[RigaDettaglio alloc] init];
        
        rigaDettaglio.codart = @"";
        rigaDettaglio.descrizione = @"";
        rigaDettaglio.quantita = [NSNumber numberWithDouble:1.000];
        rigaDettaglio.prezzo = [NSNumber numberWithDouble:0.00];
        rigaDettaglio.sc1 = [NSNumber numberWithDouble:0.000];
        rigaDettaglio.sc2 = [NSNumber numberWithDouble:0.000];
        rigaDettaglio.sc3 = [NSNumber numberWithDouble:0.000];
        rigaDettaglio.sc4 = [NSNumber numberWithDouble:0.000];
        rigaDettaglio.unmisura = @"";
        rigaDettaglio.totaleivato = [NSNumber numberWithDouble:0.000];
        rigaDettaglio.totimponibile = [NSNumber numberWithDouble:0.000];
        rigaDettaglio.totiva = [NSNumber numberWithDouble:0.000];
        
        rigaDettaglio.nuovo = [NSNumber numberWithBool:YES];
        modelRiga = rigaDettaglio;
        [self performSegueWithIdentifier:@"segueEditRigaDettaglio" sender:self];
        
//        [righeDettaglio addObject:rigaDettaglio];
//        [self.tableView reloadData];
    } else if (editingStyle == UITableViewCellEditingStyleNone){
        rigaAttuale = (int)indexPath.row;
        [self performSegueWithIdentifier:@"segueEditRigaDettaglio" sender:self];
    }
    
    //    [self dismissViewControllerAnimated:YES completion:nil];
    
    
}


-(void)prepareForSegue:(UIStoryboardPopoverSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"segueEditRigaDettaglio"]){
        UINavigationController *navigationController = segue.destinationViewController;

        RigaDettaglioEditVC *destViewController = [navigationController viewControllers][0];
//        destViewController.modelTesta = modelTesta;
//        destViewController.modelCliente = modelCliente;
//        destViewController.modelDettaglio = modelDettaglio;
        destViewController.modelTesta = modelTesta;
        destViewController.modelRiga = modelRiga;
        destViewController.delegate = self;

    }
}



// Delegates


- (IBAction)btnAnnulla:(id)sender {
    [self.delegate ordineRigheVCDidCancel:self];

}

- (IBAction)btnConferma:(id)sender {
    [self.delegate ordineRigheVC:self didViewRighe:righeDettaglio];
}


- (IBAction)btnModificaRiga:(id)sender {
    
    UIButton *senderButton = (UIButton *)sender;
    NSIndexPath *path = [NSIndexPath indexPathForRow:senderButton.tag inSection:0];
    RigaDettaglio *rigaDettaglio = [righeDettaglio objectAtIndex:[path row]];
    rigaDettaglio.nuovo = [NSNumber numberWithBool:NO];
    rigaAttuale = (int)path.row;
    modelRiga = rigaDettaglio;
    
    [self performSegueWithIdentifier:@"segueEditRigaDettaglio" sender:self];
}



// RIGA DETTAGLIO

-(void) rigaDettaglioEditVCDidCancel:(RigaDettaglioEditVC *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void) rigaDettaglioEditVC:(RigaDettaglioEditVC *)controller didEditRiga:(RigaDettaglio *)rigaDettaglio
{
    
    modelRiga = rigaDettaglio;
    
    // rimpiazzare i campi nella colonna giusta: se aggiungo o se modifico riga
    if (modelRiga.nuovo == [NSNumber numberWithBool:YES]){
        // aggiungo record alla fine
        modelRiga.nuovo = [NSNumber numberWithBool:NO];
        [righeDettaglio addObject:modelRiga];
//        [self.tableView reloadData];
    } else {
        righeDettaglio[rigaAttuale] = modelRiga;
    }
    
    [self.tableView reloadData];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}



@end
